// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <unordered_map>

#include <pollux/core/plan_node.h>
#include <pollux/sql/presto_sql.h>
#include <pollux/sql/reference_query_runner.h>

namespace kumo::pollux::sql {
    bool ReferenceQueryRunner::isSupportedDwrfType(const TypePtr &type) {
        if (type->isDate() || type->isIntervalDayTime() || type->is_unKnown()) {
            return false;
        }

        for (auto i = 0; i < type->size(); ++i) {
            if (!isSupportedDwrfType(type->childAt(i))) {
                return false;
            }
        }

        return true;
    }

    melon::F14FastMap<std::string, std::vector<pollux::RowVectorPtr> >
    ReferenceQueryRunner::getAllTables(const core::PlanNodePtr &plan) {
        melon::F14FastMap<std::string, std::vector<pollux::RowVectorPtr> > result;
        if (const auto valuesNode =
                std::dynamic_pointer_cast<const core::ValuesNode>(plan)) {
            result.insert({getTableName(*valuesNode), valuesNode->values()});
        } else {
            for (const auto &source: plan->sources()) {
                auto tablesAndNames = getAllTables(source);
                result.insert(tablesAndNames.begin(), tablesAndNames.end());
            }
        }
        return result;
    }
} // namespace kumo::pollux::sql
